"""Pylons environment configuration"""
import os

from pylons import config
from sqlalchemy import engine_from_config

from mako.lookup import TemplateLookup
from pylons.error import handle_mako_error


import cibynet.lib.app_globals as app_globals
import cibynet.lib.helpers
from cibynet.config.routing import make_map
from cibynet.config import passwords


def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='cibynet',
                    template_engine='mako', paths=paths)
    
    config['pylons.strict_c'] = False

    globals = app_globals.Globals(SIGNOUT_PART="signout/",
                                  FEEDBACK_PART="feedback/",
                                  cibynet_email="cibynet-admins@googlegroups.com",
                                  confirmation_email=False)
    config['routes.map'] = make_map(globals)
    config['pylons.app_globals'] = config['pylons.g'] = globals
    config['pylons.h'] = cibynet.lib.helpers

    # Customize templating options via this variable
    tmpl_options = config['buffet.template_options']
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', output_encoding='utf-8',
        imports=['from webhelpers.html import escape'],
        default_filters=['escape'])


    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    
    # Load passwords
    config['passwords'] = passwords.load_passwords(app_conf)
    
    #db
    from cibynet.model import init_model
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine)

